﻿#region

using System;
using System.Collections.Async;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using AngleSharp.Extensions;
using AngleSharp.Parser.Html;
using DevLib.ExtensionMethods;
using log4net;
using Newtonsoft.Json.Linq;
using RestSharp;
using SharpCompress.Archives;
using wsy.ext.restsharp;
using static wsy.ext.restsharp.Extend;

#endregion

namespace Nuget本地升级46
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            Cfglog4.Cfg();
            InitializeComponent();
            this.Icon = Properties.Resources.download_to_computer;

        }
        private void Form1_Load(object sender, EventArgs e)
        {
            NugetDirPath = Environment.CurrentDirectory;
            dataGridView1.SetPropertyValue("DoubleBuffered", true, false);
            FolderBrowserDialog fbd = new FolderBrowserDialog
            {
                SelectedPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)
            };
            if (fbd.ShowDialog() == DialogResult.OK) NugetDirPath = fbd.SelectedPath;
            Enumfiles(NugetDirPath);
            dataGridView1.DataSource = Models;
        }

        /// <summary>
        ///     枚举文件
        /// </summary>
        /// <param name="dirpath"></param>
        public async void Enumfiles(string dirpath)
        {
            ILog logger = LogManager.GetLogger(GetType());
            string[] files = Directory.GetFiles(dirpath, "*.nupkg");
            if (files.Length == 0)
            {
                logger.Error($"{dirpath} is empty .");
                return;
            }
            await files.ParallelForEachAsync(async s => { await EnumEachfile(s); });
        }

        /// <summary>
        ///     处理枚举每个文件
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        private Task EnumEachfile(string file)
        {
            return Task.Run(() =>
            {
                ILog logger = LogManager.GetLogger(GetType());
                var archive = ArchiveFactory.Open(file);
                IArchiveEntry nuspec = null;
                try
                {
                    nuspec = archive.Entries.First(s => s.Key.EndsWith(".nuspec"));
                }
                catch (Exception e)
                {
                    logger.Error(e);
                    return false;
                }
                if (nuspec == null)
                {
                    logger.Error($"{file}");
                    return false;
                }
                var d = nuspec.LastModifiedTime;
                StreamReader sr = new StreamReader(nuspec.OpenEntryStream());
                string text = sr.ReadToEnd();
                sr.Close();
                sr.Dispose();
                HtmlParser parser = new HtmlParser();
                var doc = parser.Parse(text);
                var i = doc.QuerySelector("metadata>id").Text();
                var v = doc.QuerySelector("metadata>version").Text();

                if (string.IsNullOrEmpty(i) || string.IsNullOrEmpty(v))
                {
                    logger.Error($"{file} id:{i} version:{v} is error .");
                    return true;
                }


                lock (Models)
                {
                    Model singleOrDefault = Models.SingleOrDefault(s => s.Id == i);
                    if (singleOrDefault == null)
                    {
                        Model m = new Model();
                        m.Id = i;
                        m.Version = v.ToUpper();
                        m.Dt = d;
                        Invoke(new Action(() => { Models.Add(m); }));
                    }
                    else
                    {
                        if (d > singleOrDefault.Dt)
                        {
                            singleOrDefault.Dt = d;
                            singleOrDefault.Version = v.ToUpper();
                        }
                    }
                }
                return true;
            });
        }

        private async void button1_Click(object sender, EventArgs e)
        {
            button2.Enabled = false;
            button1.Enabled = false;
            timer1.Enabled = true;
            radioButton1.Enabled = false;
            radioButton2.Enabled = false;
            ParallelOptions opt = new ParallelOptions();
            opt.MaxDegreeOfParallelism = 10;
            var fo = Task.Run(() => { Parallel.ForEach(Models, opt, GetItem); });
            await fo;
            button1.Enabled = true;
            timer1.Enabled = false;
            int c = Models.Count;
            List<Model> removeList = new List<Model>();
            for (int i = 0; i < c; i++)
                lock (Models)
                {
                    if (!Models[i].TobeUpdate && Models[i].State == "finished") removeList.Add(Models[i]);
                }
            foreach (Model i in removeList)
                lock (Models)
                {
                    Models.Remove(i);
                }
            dataGridView1.ReadOnly = false;
            for (int i = 0; i < dataGridView1.Columns.Count; i++)
            {
                if (i == 5)
                    continue;
                dataGridView1.Columns[i].ReadOnly = true;
            }

            button2.Enabled = true;
            radioButton1.Enabled = true;
            radioButton2.Enabled = true;
        }

        public void GetItem(Model m)
        {
            m.State = "cheacking";
            m.TobeUpdate = false;
            ILog logger = LogManager.GetLogger(GetType());
            string apisearch = "https://api-v2v3search-0.nuget.org";
            if (Cnblogs)
            {
                apisearch = "https://nuget.cnblogs.com/api-v2v3search-0";
            }
            RestClient rc = new RestClient(apisearch);
            RestRequest req = new RestRequest("query");
            req.Timeout = 5000;
            req.AddQueryParameter("q", m.Id);
            req.AddQueryParameter("take", "30");
            req.AddQueryParameter("prerelease", "true");
            var res = rc.Get(req);
            if (res.ErrorException != null)
            {
                m.State = "cheack out of time";
                return;
            }
            JObject resjson = JObject.Parse(res.Content);
            JToken data;
            try
            {
                data = resjson["data"].FirstOrDefault(s => s["id"].Value<string>().ToUpper() == m.Id.ToUpper());
                if (data == null)
                {
                    logger.Fatal("can't find " + m.Id);
                    return;
                }
                m.LastVersion = data["version"].Value<string>().ToUpper();
            }
            catch (Exception e)
            {
                logger.Error(e);
                m.State = "cheacking faild";
                return;
            }
            m.State = "finished";
            if (m.LastVersion != m.Version)
            {
                try
                {
                    Version v1 = new Version(m.LastVersion);
                    Version v2 = new Version(m.Version);
                    if (v1.CompareTo(v2) == 0)
                        return;
                    int v1B = v1.Build == -1 ? 0 : v1.Build;
                    int v1M = v1.Major == -1 ? 0 : v1.Major;
                    int v1Mr = v1.MajorRevision == -1 ? 0 : v1.MajorRevision;
                    int v1Mi = v1.Minor == -1 ? 0 : v1.Minor;
                    int v1Mir = v1.MinorRevision == -1 ? 0 : v1.MinorRevision;
                    int v1R = v1.Revision == -1 ? 0 : v1.Revision;
                    int v2B = v2.Build == -1 ? 0 : v2.Build;
                    int v2R = v2.Revision == -1 ? 0 : v2.Revision;
                    int v2M = v2.Major == -1 ? 0 : v2.Major;
                    int v2Mr = v2.MajorRevision == -1 ? 0 : v2.MajorRevision;
                    int v2Mi = v2.Minor == -1 ? 0 : v2.Minor;
                    int v2Mir = v2.MinorRevision == -1 ? 0 : v2.MinorRevision;
                    if (v1B == v2B && v1R == v2R&& v1M==v2M &&v1Mr==v2Mr&&v1Mi==v2Mi&&v1Mir==v2Mir)
                        return;
                }
                catch (Exception)
                {
                    // ignored
                }
                var idjson =
                    data["versions"].FirstOrDefault(s => s["version"].Value<string>() == data["version"].Value<string>());
                rc = new RestClient(idjson["@id"].Value<string>());
                req = new RestRequest();
                req.Timeout = 5000;
                JObject contentJObject=null;
                try
                {
                    contentJObject = JObject.Parse(rc.Get(req).Content);
                }
                catch (Exception e)
                {
                   logger.Fatal(e);
                    m.State = "cheacking faild";
                    return;
                }
                
                m.Pageurl = contentJObject["packageContent"].Value<string>();
                m.TobeUpdate = true;
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            dataGridView1.Refresh();
        }

        private async void button2_Click(object sender, EventArgs e)
        {
            ILog logger = LogManager.GetLogger(GetType());
            button2.Enabled = false;
            button1.Enabled = false;
            timer1.Enabled = true;
            dataGridView1.ReadOnly = true;
            var tobedown = Models.Where(s => s.TobeUpdate);
            try
            {
                await tobedown.ParallelForEachAsync(async s => { await downfile(s); }, 10);
            }
            catch (Exception exp)
            {
                logger.Error(exp);
            }
            dataGridView1.Refresh();
            timer1.Enabled = false;
            button2.Enabled = true;
            button1.Enabled = true;
        }

        private async Task downfile(Model m)
        {
            ILog logger = LogManager.GetLogger(GetType());

            try
            {
                var file = Path.Combine(NugetDirPath, Path.GetFileName(m.Pageurl));
                RestClient rc = new RestClient(m.Pageurl);
                await rc.DownloadDataByProgress(new RestRequest(), file, new Extend.Progress<DownloadDataStruct>(s =>
                {
                    m.State = s.CurrentSize + "/" + (s.CurrentSize / (double) s.FinalFileSize).ToString("P");
                    if (s.CurrentSize == s.FinalFileSize)
                    {
                        m.State = "saved";
                        m.Version = m.LastVersion;
                    }
                }));
            }
            catch (Exception e)
            {
                m.State = "download error";
                logger.Error(e);
            }
        }

        #region field

        public static string NugetDirPath { get; set; }
        public BindingList<Model> Models = new BindingList<Model>();
        public static bool Cnblogs { get; set; }

        #endregion

        private void radioButton2_CheckedChanged(object sender, EventArgs e)
        {
            Cnblogs = false;
            if (radioButton2.Checked)
            {
                Cnblogs = true;
            }
        }
    }
}